package main

import (
	"cronexpr"
	"time"
	"fmt"
)

type CronJob struct {
	e *cronexpr.Expression
	t time.Time
}

func MakeJob(jobStr string) *CronJob {
	job := CronJob{}
	job.e = cronexpr.MustParse(jobStr)
	job.t = job.e.Next(time.Now())
	return &job
}

func ScheduleJob(t map[string]*CronJob)  {
	for{
		now := time.Now()
		for name, job := range t {
			if job.t.Before(now) || job.t.Equal(now) {
				DoJob(name)
				job.t = job.e.Next(now)
			}
		}
		time.Sleep(100 * time.Millisecond)
	}
}

func DoJob(jobName string)  {
	fmt.Println("run", jobName)
}

func main() {
	jobs := make(map[string]*CronJob)
	jobs["job1"] = MakeJob("*/1 * * * * * *")
	jobs["job2"] = MakeJob("*/2 * * * * * *")
	
	go ScheduleJob(jobs)

	time.Sleep(10 * time.Second)
}
